package com.test.mina2.example.message;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

// 2编码器
public class CmccSpicEncoder extends ProtocolEncoderAdapter {

	private final Charset charSet;

	public CmccSpicEncoder(Charset charSet) {
		this.charSet = charSet;
	}

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		SmsObject sms = (SmsObject) message;
		CharsetEncoder encoder = charSet.newEncoder();
		// 将传输的信息设置到缓冲区并且设定为自动扩展
		IoBuffer ioBuffer = IoBuffer.allocate(100).setAutoExpand(true);
		String stateLine = "M sip:wap.fetion.com.cn SIP-C/2.0";
		String sender = sms.getSender();
		String receiver = sms.getReceiver();
		String smsContent = sms.getMessage();
		// 按照指定传输协议组装起来put到缓冲区
		ioBuffer.putString(stateLine + "\n", encoder);
		ioBuffer.putString("S:" + sender + "\n", encoder);
		ioBuffer.putString("R:" + receiver + "\n", encoder);
		ioBuffer.putString("L:" + (smsContent.getBytes(charSet).length) + "\n", encoder);
		ioBuffer.putString(smsContent, encoder);
		// 组装完毕后调用flip(),必须在write之前
		ioBuffer.flip();
		// 将缓冲区的数据输出
		out.write(ioBuffer);
	}
}
